package com.service.utility.common;

import com.github.kevinsawicki.http.HttpRequest;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.service.utility.jwt.JWTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * token 请求/校验工具类
 */
public class TokenUtil {
    private static Logger logger = LoggerFactory.getLogger(TokenUtil.class);


    /**
     * 通过Token获取UserID
     * @param token token
     * @return userId
     */
    public static String getUserIdByToken(String token) {
        String payload = JWTUtil.getPayloadStringByToken(token);
        return JsonIterator.deserialize(payload).get("userId").toString();
    }

    /**
     * 校验token
     *
     * @param URL           校验Token接口
     * @param authorization 认证信息
     * @param token         token
     * @param uuid          uuid
     * @throws Exception
     */
    public static void validateToken(String URL, String authorization, String token, String uuid) throws Exception {
        HttpRequest httpRequest = HttpRequest.post(URL).header("api-version", 1.0)
                .header("Authorization", authorization)
                .acceptJson().contentType("application/json", "UTF-8")
                .send(token.getBytes());

        String body = httpRequest.body();
        int code = httpRequest.code();
        logger.info("校验token[uuid:{}, responseCode:{}, responseBody:{}]", uuid, code, body);

        Any bodyAny = JsonIterator.deserialize(body);
        int status = bodyAny.get("status").toInt();

        if (HttpStatus.OK.value() != code || HttpStatus.OK.value() != status) {
            logger.info("校验token失败[uuid:{}, responseCode:{}, responseStatus:{}]", uuid, code, status);
            throw new Exception("token校验失败");
        }
        //token校验通过
        logger.info("校验token成功[uuid:{}, responseCode:{}, responseStatus{}]", uuid, code, status);
    }

    /**
     * 请求生成Token
     *
     * @param URL           生成Token接口
     * @param headPortrait  头像
     * @param phone         电话
     * @param userId        用户id
     * @param authorization 认证信息
     * @param uuid          uuid
     * @return
     */
    public static String generateToken(String URL, String headPortrait, String phone, String userId, String authorization, String uuid) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("headPortrait", headPortrait);
        map.put("loginName", phone);
        map.put("source", "END_USER");
        map.put("userId", userId);
        map.put("roleIdList", null);
        String serialize = JsonStream.serialize(map);
        HttpRequest httpRequest = HttpRequest.post(URL).header("api-version", 1.0)
                .header("Authorization", authorization)
                .acceptJson().contentType("application/json", "UTF-8")
                .send(serialize.getBytes());

        String body = httpRequest.body();
        int httpCode = httpRequest.code();
        logger.info("生成token[uuid:{}, responseCode:{}, responseBody:{}]", uuid, httpCode, body);

        Any bodyAny = JsonIterator.deserialize(body);
        int status = bodyAny.get("status").toInt();

        if (HttpStatus.OK.value() != httpCode || HttpStatus.OK.value() != status) {

            logger.info("生成token失败[uuid:{}, responseCode:{}, responseStatus:{}]", uuid, httpCode, status);
            throw new Exception("生成token 失败 responseCode:" + httpCode + ", responseStatus:" + status);
        }
        String token = bodyAny.get("data").get("token").toString();
        logger.info("生成token成功[uuid:{}, token:{}, phone{}]", uuid, token, phone);
        return token;
    }


}
